package com.dosin.crowno.utils;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import okhttp3.*;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author huidongma
 */
@Data
public class HgaHelper {
    private String url;
    private String uId;
    public HgaHelper(String url, String uId) {
        this.url = url;
        this.uId = uId;
    }

    /**
     * 按照日期获取报表数据（筛选条件可根据实际业务调整）
     * @param start
     * @param end
     * @return
     */
    public JSONObject getOrders(Date start, Date end){
        RequestBody formbody = new FormBody.Builder()
                .add("login_layer","co")
                .add("uid",this.getUId())
                .add("langx","zh-cn")
                .add("ver","version-7-31")
                .add("p","check_report")
                .add("date_start", DateUtil.format(start,"yyyy-MM-dd"))
                .add("date_end",DateUtil.format(end,"yyyy-MM-dd"))
                .add("result_type","N")
                .add("report_kind","A")
                .add("gtype","")
                .add("wtype","")
                .build();

        return postUrl(formbody);
    }

    private JSONObject postUrl(RequestBody formbody){
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .sslSocketFactory(createSSLSocketFactory(),new TrustAllManager())
//                .sslSocketFactory(createSSLSocketFactory())
                .hostnameVerifier((s, sslSession) -> true)
                .build();
        Request request = null ;
        try {
            request = new Request.Builder()
                    .url(this.getUrl()+"/transform.php")
                    .post(formbody)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Connection","close")
                    .addHeader("User-Agent","Mozilla/5.0(Macintosh;IntelMacOSX10_15_7)AppleWebKit/537.36(KHTML,likeGecko)Chrome/91.0.4472.77Safari/537.36")
                    .addHeader("Accept","*/*")
//                    .addHeader("Accept-Encoding","gzip,deflate,br")
                    .addHeader("Cache-Control","no-cache")
                    .addHeader("Accept-Language","zh-CN,zh;q=0.9")
                    .addHeader("Host",new URL(this.getUrl()).getHost())
                    .addHeader("Origin",getUrl())
                    .addHeader("Pragma","no-cache")
                    .addHeader("Referer",getUrl())
                    .addHeader("sec-ch-ua","\"Not;ABrand\";v=\"99\",\"GoogleChrome\";v=\"91\",\"Chromium\";v=\"91\"")
                    .addHeader("sec-ch-ua-mobile","?0")
                    .addHeader("Sec-Fetch-Dest","empty")
                    .addHeader("Sec-Fetch-Mode","cors")
                    //Content-Length:175
                    .addHeader("Sec-Fetch-Site","same-origin") .build();;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        Response response = null;
        try {
            response = client.newCall(request).execute();
            if(response.body()!=null){
                JSONObject jsonObject= JSON.parseObject(response.body().string());
                return jsonObject;
            }
        } catch (IOException exception) {
//            log.error("",exception);
            exception.printStackTrace();
        }
        return null;
    }

    private static SSLSocketFactory createSSLSocketFactory () {

        SSLSocketFactory sSLSocketFactory = null;

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllManager()}, new SecureRandom());
            sSLSocketFactory = sc.getSocketFactory();
        } catch (Exception e) {
//            log.info(e.getMessage(), e);
        }

        return sSLSocketFactory;
    }

    private static class TrustAllManager implements X509TrustManager {

        @Override
        public void checkClientTrusted (java.security.cert.X509Certificate[] x509Certificates,
                                        String s) throws java.security.cert.CertificateException {
        }

        @Override
        public void checkServerTrusted (java.security.cert.X509Certificate[] x509Certificates,
                                        String s) throws java.security.cert.CertificateException {
        }


        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers () {
            return new X509Certificate[0];
        }
    }


}
